package com.cyh.structurealgorithm;

public class InsertValueSearch {
    public static void test() {
        int arr[] = {-8, -2, -2, -1, 3, 3, 5, 9, 10, 10, 11};
        int resIndex = insertValueSearch(arr, 0, arr.length - 1, 9);
        System.out.println("查找的下标：resIndex = " + resIndex);
    }

    public static int insertValueSearch(int[] arr, int left, int right, int findVal) {
        if(left > right || findVal < arr[0] || findVal > arr[arr.length - 1]) { //三个条件必须，否则mid可能越界
            return -1;
        }
        int mid = left + (right - left) * (findVal - arr[left])/(arr[right] - arr[left]);
        int midVal = arr[mid];
        if(findVal > midVal) {
            return insertValueSearch(arr, mid + 1, right, findVal);
        } else if(findVal < midVal) {
            return insertValueSearch(arr, left, mid -1, findVal);
        } else {
            return mid;
        }
    }
}
